from rest_framework import serializers
from django_redis import get_redis_connection
from rest_framework_jwt.settings import api_settings

from oauth.utils import OAuthQQ
from users.models import User
from .models import OAuthQQUser


class OAuthQQUserSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='操作凭证', write_only=True)
    token = serializers.CharField(label='登录状态token', read_only=True)
    mobile = serializers.RegexField(label='手机号', regex=r'1[3-9]\d{9}')

    class Meta:
        model = User
        # 接收过来的参数有mobile, password, sms_code, access_token
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'id', 'username', 'token')
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码',
                }
            },
        }
        # 现在的情况是，已经确认用户是第一次使用ＱＱ登录，也就是openid是空的
        # 通过用户发送的手机号码查询是否有绑定记录
    # 这里是检验各个参数的过程
    def validate(self, attrs):
        # 检验access_token
        access_token = attrs['access_token']
        open_id = OAuthQQ.check_bind_user_access_token(access_token)
        if not open_id:
            raise serializers.ValidationError('无效的access_token')
        attrs['openid'] = open_id
        mobile = attrs['mobile']


        # 验证短信验证码以及密码
        redis_conn = get_redis_connection('verify_codes')
        real_code = redis_conn.get("sms_%s" % mobile)
        if not real_code:
            raise serializers.ValidationError('无效的短信验证码')
        sms_code = attrs['sms_code']
        if real_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')
        password = attrs['password']
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            pass
        else:
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user

        return attrs

    # 这里是创建的过程
    def create(self, validated_data):
        mobile = validated_data['mobile']
        password = validated_data['password']
        openid = validated_data['openid']
        # validated_data　是经过校验的参数
        # 因为都设计到要设置openid，所以，先给没有用户的进行创建
        user = validated_data.get('user', None)
        if not user:
            # 如果没有，就先创建对象
            user = User.objects.create_user(mobile=mobile, username=mobile, password=password)
        # 现在都有user了，可以给user加上openid了
        OAuthQQUser.objects.create(user=user, openid=openid)
        # 签发jwt token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        # 在序列化器中，将user对象保存到类视图对象中
        self.context['view'].user = user
        # 返回数据
        return user








